package com.hyd.tweet.twitter.command;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Presence;
import com.hyd.tweet.Application;
import com.hyd.tweet.twitter.TwitterUserUtils;
import com.hyd.tweet.user.User;
import com.hyd.tweet.user.UserManager;
import com.hyd.tweet.util.Cache;
import com.hyd.tweet.util.DateUtils;
import com.hyd.tweet.util.StringUtils;
import com.hyd.tweet.xmpp.TwitterUpdaterServlet;
import com.hyd.tweet.xmpp.XMPPUtils;
import twitter4j.TwitterException;

import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

/**
 * (description)
 *
 * @author yiding.he
 */
@SuppressWarnings({"unchecked"})
public class DebugCommand extends Command {

    @Override
    public List<String> processCommand() throws TwitterException {

        if (!Application.isAdmin(user)) {
            return Arrays.asList("——您不是管理员，只有管理员可以调试。");
        }

        if (arguments.isEmpty()) {
            return Arrays.asList("——可用命令：me, cache, update, init");
        }

        String cmd = StringUtils.combine(arguments, 0);

        if (cmd.equals("me")) {
            return Arrays.asList(
                    user.toString(),
                    twitterUserToString(twitterUser),
                    getXmppStatus(user),
                    getTimeStatus(user)
            );

        } else if (cmd.equals("update")) {
            TwitterUpdaterServlet.update();
            return Arrays.asList("——已尝试自动更新。");

        } else if (cmd.equals("init")) {
            Cache.clear();
            UserManager.preloadUsers();
            return Arrays.asList("——已清空缓存。");
        }

        return Arrays.asList("未知调试命令");
    }

    private String getTimeStatus(User user) throws TwitterException {
        int utcOffset = TwitterUserUtils.getCurrentTwitterUser(user.getAccount()).getUtcOffset();

        Calendar c = DateUtils.getGMTTime();
        c.add(Calendar.SECOND, utcOffset);
        int h = c.get(Calendar.HOUR_OF_DAY);

        return "Now: " + c.getTime() + ", Now hour: " + h;
    }

    private String getXmppStatus(User user) {
        Presence presence = XMPPUtils.getXMPP().getPresence(new JID(user.getAccount()));
        return "XMPP Presence: " + presence.getPresenceType() + "/"
                + presence.getPresenceShow() + ", " + presence.getStatus();
    }

    private String twitterUserToString(twitter4j.User user) {
        return user.getScreenName() + "{ location=" + user.getLocation() +
                ",timeZone=" + user.getTimeZone() + ",utcOffset=" + user.getUtcOffset() + "}";
    }

}
